package net.tmaize.service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;

import net.tmaize.dao.impl.DetailDaoImpl;
import net.tmaize.dao.impl.HotDaoImpl;
import net.tmaize.entity.List_hot;
import net.tmaize.entity.News_detail;
import net.tmaize.entity.News_hot;

public class ShowHot extends HttpServlet {

	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Content-type", "text/html;charset=UTF-8");
		// 不缓存
//		response.setHeader("Pragma", "No-cache");
//		response.setHeader("Cache-Control", "no-cache");
//		response.setDateHeader("Expires", -1);
		
		//虽然设置缓存在出错时点击这个超链接会一直显示错误界面，但是这个页面比较消耗时间还是设置缓存为好
		response.setDateHeader("Last-Modified", new Date().getTime());
		response.setDateHeader("Expires", new Date().getTime() + 15 * 60 * 1000);
		response.setHeader("Cache-Control", "public");
		response.setHeader("Pragma", "Pragma");

		try {
			// 热门消息里面只有缩略图，还要根据news_id获取原文的api来获取大图
			HotDaoImpl hotDaoImpl = new HotDaoImpl();
			News_hot hot = hotDaoImpl.getHot();
			DetailDaoImpl detailDaoImpl = new DetailDaoImpl();
			List<News_detail> details = new ArrayList<News_detail>();
			for (List_hot recent : hot.getRecent()) {
				details.add(detailDaoImpl.getDetail(recent.getNews_id()));
			}
			request.setAttribute("details", details);
			RequestDispatcher requestDispatcher = this.getServletContext().getRequestDispatcher("/WEB-INF/jsp/hot.jsp");
			requestDispatcher.forward(request, response);
		} catch (JSONException | IOException e) {
			// 解析json失败
				response.sendRedirect(request.getContextPath() + "/error.html");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
